package cn.com.nes.site.rocketmq.handler;


import cn.com.nes.mybatis.agent.ope.entity.ProductSeriesAndEnergy;
import cn.com.nes.mybatis.agent.system.entity.CompanyMerchant;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.ProductAddRequest;
import cn.com.nes.site.entity.ProductAttrValueAddRequest;
import cn.com.nes.site.entity.em.system.DictTypeEnum;
import cn.com.nes.site.entity.vo.product.GGoodsVO;
import cn.com.nes.site.entity.vo.product.SaveProductSeriesAndEnergyVO;
import cn.com.nes.site.rocketmq.strategy.MessageHandler;
import cn.com.nes.site.rocketmq.strategy.Topic;
import cn.com.nes.site.service.product.GGoodsService;
import cn.com.nes.site.service.product.ProductSeriesAndEnergyService;
import cn.com.nes.site.service.system.company.CompanyMerchantService;
import cn.com.nes.site.service.system.dict.TParamService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Topic("mall2agent_product_topic")
@Component
@Slf4j
public class Mall2AgentProductHandler implements MessageHandler {

    @Resource
    GGoodsService gGoodsService;

    @Resource
    ProductSeriesAndEnergyService productSeriesAndEnergyService;

    @Resource
    private CompanyMerchantService companyMerchantService;

    @Resource
    private TParamService tParamService;

    @Override
    public void handleMessage(MessageExt message) {
        // 解析消息内容
        String messageBody = new String(message.getBody());
        System.out.println("处理 mall2agent_product_topic 消息: " + messageBody);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            ProductAddRequest product = objectMapper.readValue(messageBody, ProductAddRequest.class);

            // 获取公司商铺信息
            CompanyMerchant companyMerchant = companyMerchantService.selectByCompanyMerchantId(null, product.getMerId().toString());
            if (companyMerchant != null) {
                Long brandId = handleProductSeriesAndEnergy(product, companyMerchant);

                saveProduct(product,brandId,companyMerchant.getCompanyId());
            }

        } catch (IOException e) {
            System.err.println("消息解析失败: " + e.getMessage());
            log.error("异常详情:" + e);
            throw new RuntimeException("消息处理失败", e);
        }
    }

    private Long  handleProductSeriesAndEnergy(ProductAddRequest product, CompanyMerchant companyMerchant) {
        // 根据品牌名称检查是否已经存在品牌，没有则添加
        ProductSeriesAndEnergy productSeriesEnergy = productSeriesAndEnergyService.getbrandIdByBrandName(product.getBrandName(), companyMerchant.getCompanyId());
        if (productSeriesEnergy == null) {
            productSeriesEnergy = new ProductSeriesAndEnergy();
            productSeriesEnergy.setNodeName(product.getBrandName());
            productSeriesEnergy.setRemark(product.getBrandName() + "默认品牌系列");
            productSeriesEnergy.setNodeType(0);
            productSeriesEnergy.setSort(0);
            productSeriesEnergy.setParentId(1L);
            productSeriesEnergy.setLevel(1);
            productSeriesEnergy.setCompanyId(companyMerchant.getCompanyId());
            productSeriesEnergy.setEnable(true);
            productSeriesEnergy.setDeleted(false);
            productSeriesEnergy.setGmtCreate(new Date());

            SaveProductSeriesAndEnergyVO saveProductSeriesAndEnergyVO=new SaveProductSeriesAndEnergyVO();
            BeanUtils.copyProperties(productSeriesEnergy,saveProductSeriesAndEnergyVO );
            // 保存品牌系列
            PageData pageData = productSeriesAndEnergyService.saveProductSeriesAndEnergy(saveProductSeriesAndEnergyVO);
            return Long.valueOf(pageData.getKey());
        }
        return productSeriesEnergy.getId();
    }

    private void saveProduct(ProductAddRequest product,Long brandId,String companyId) {
        GGoodsVO gGoodsVO = new GGoodsVO();

        // 根据产品分类名获取能源类型ID
        String[] parts = product.getCategoryName().split(":");
        String name = parts[parts.length - 1].trim();
        ProductSeriesAndEnergy productSeriesAndEnergy = productSeriesAndEnergyService.getIdByNodeName(name);
        if (productSeriesAndEnergy != null) {
            gGoodsVO.setEnergyType(productSeriesAndEnergy.getId());
        }

        gGoodsVO.setUnit(tParamService.getValueByName(DictTypeEnum.UNIT_OF_MEASUREMENT.getParamType(), product.getUnitName()));
        gGoodsVO.setGoodsName(product.getName());
        gGoodsVO.setBrandId(brandId);
        gGoodsVO.setEnable(true);
        gGoodsVO.setTabPosition("01");
        gGoodsVO.setCompanyId(companyId);
        gGoodsVO.setLogo(product.getImage());

        // 获取并处理产品属性值
        List<ProductAttrValueAddRequest> attrValues = product.getAttrValue();
        if (attrValues != null && !attrValues.isEmpty()) {
            for (ProductAttrValueAddRequest attrValue : attrValues) {
                gGoodsVO.setGoodsCode(attrValue.getBarCode());
                gGoodsVO.setPrice(attrValue.getPrice());
                gGoodsVO.setPackingSize(attrValue.getAttrValue());
                gGoodsService.saveGoods(gGoodsVO);
            }
        } else {
            gGoodsService.saveGoods(gGoodsVO);
        }
    }

}
